package com.kotlin.book.fragments

import android.content.Intent
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.kotlin.book.R
import com.kotlin.book.activity.DetailActivity
import com.kotlin.book.adapter.BookItemColumn4Adapter
import com.kotlin.book.adapter.HomeItemWeekTypeAdapter
import com.kotlin.book.api.BookApi
import com.kotlin.book.api.TypeApi
import com.kotlin.book.databinding.FragmentHomeIndexBinding
import com.kotlin.book.entry.Swiper
import com.kotlin.book.util.Util

class HomeFragmentIndex : Fragment() {
    private var list = mutableListOf<Swiper>()
    private lateinit var binding: FragmentHomeIndexBinding
    private val handler = Handler(Looper.getMainLooper())
    private var currentPage = 0
    private var typeId: Int? = null

    private val runnable: Runnable = object : Runnable {
        override fun run() {
            // 切换到下一个页面
            currentPage = (currentPage + 1) % list.size
            binding.swiperViewPager.currentItem = currentPage
            // 重新启动这个任务
            handler.postDelayed(this, 3000) // 每3秒切换一次
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentHomeIndexBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 获取轮播图
//        HttpApi.getSwiper { response ->
//            response?.let {
//                list.add(it)
//                list.add(it) // 添加多次，模拟多个条目
//                requireActivity().runOnUiThread {
//                    val adapter = HomeSwiperItemAdapter(list)
//                    binding.swiperViewPager.adapter = adapter
//                    handler.postDelayed(runnable, 3000)
//                }
//            }
//        }

        //为你推荐
        binding.homeIndexRecommend.layoutManager = GridLayoutManager(requireActivity(), 4)
        BookApi.getRecommendList(null) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    binding.homeIndexRecommend.adapter =
                        BookItemColumn4Adapter(mapOf("authorName" to true), it)
                }
            }
        }

        //近期热门
        binding.homeIndexHot.layoutManager = GridLayoutManager(requireActivity(), 4)
        BookApi.getHotList(mapOf("pageSize" to 5)) { response ->
            response?.data?.let { data ->
                requireActivity().runOnUiThread {
                    binding.one.setOnClickListener {
                        // 页面跳转
                        val intent = Intent(requireContext(), DetailActivity::class.java)
                        val bundle = Bundle()
                        // 传参
                        bundle.putInt("id", data[0].id)
                        intent.putExtras(bundle)
                        requireContext().startActivity(intent)
                    }
                    binding.oneTitle.text = data[0].name
                    binding.oneName.text = data[0].author
                    binding.oneProfile.text = data[0].blurb
                    //处理tag
                    Util.getImage(data[0].pic, binding.oneImage, requireContext())
                    val oneTags = data[0].tag?.split(",") ?: listOf()
                    for (tag in oneTags) {
                        if (tag != "") {
                            val textView = TextView(context).apply {
                                layoutParams = LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.WRAP_CONTENT,
                                    LinearLayout.LayoutParams.WRAP_CONTENT
                                ).apply {
                                    setMargins(Util.dpToPx(12, context), 0, 0, 0) // 设置 marginStart
                                }
                                background =
                                    ContextCompat.getDrawable(
                                        context,
                                        R.drawable.home_tag_background
                                    )
                                setPadding(
                                    Util.dpToPx(10, context),
                                    Util.dpToPx(4, context),
                                    Util.dpToPx(10, context),
                                    Util.dpToPx(4, context)
                                ) // 设置 padding
                                setTextColor(
                                    ContextCompat.getColor(
                                        context,
                                        R.color.primary_color
                                    )
                                ) // 设置文本颜色
                                textSize = 12f // 设置文本大小（sp）
                                setTypeface(null, Typeface.BOLD) // 设置加粗
                                text = tag // 设置文本
                            }
                            binding.homeTagBox.addView(textView)
                        }
                    }

                    // 复制列表并删除第 0 个元素
                    val list = data.toMutableList()
                    list.removeAt(0)
                    binding.homeIndexHot.adapter =
                        BookItemColumn4Adapter(mapOf("authorName" to false), list)
                }
            }
        }

        //本周强推分类
        binding.homeWeeksType.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        TypeApi.getClassType(null) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    binding.homeWeeksType.adapter = HomeItemWeekTypeAdapter(it) { id ->
                        typeId = id
                        getWeekList()
                    }
                    typeId = it[0].id
                    getWeekList()
                }
            }
        }
    }

    //本周强推
    private fun getWeekList() {
        binding.homeIndexWeeks.layoutManager = GridLayoutManager(requireActivity(), 4)
        val form = mutableMapOf("pageSize" to 8)
        typeId?.let {
            form["typeId"] = it
        }
        BookApi.getWeekList(form) { response ->
            response?.data?.let {
                requireActivity().runOnUiThread {
                    if (binding.homeIndexWeeks.adapter == null) {
                        binding.homeIndexWeeks.adapter =
                            BookItemColumn4Adapter(mapOf("authorName" to true), it)
                    } else {
                        (binding.homeIndexWeeks.adapter as BookItemColumn4Adapter).setData(it)
                    }
                }
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        handler.removeCallbacks(runnable)
    }
}